/**
 * 根据后端给出的菜单权限匹配出前端路由
 */
import router from '@/router'
import dynamicsRoutes from '@/router/dynamics'
import type { Menu } from '@/types'
import type { RouteRecordRaw } from 'vue-router'

/**
 * 根据用户返回的菜单权限，匹配映射出定义的菜单列表
 */
export function mapRoute(userMenus: Menu[]): RouteRecordRaw[] {
  var mapRoutes: RouteRecordRaw[] = []
  const fn = (userMenus: Menu[]) => {
    for (let index = 0; index < userMenus.length; index++) {
      const userMenu = userMenus[index]
      const route = dynamicsRoutes.find((item) => item.path === userMenu.route)
      if (route) mapRoutes.push(route)
      if (userMenu.children && userMenu.children.length > 0) fn(userMenu.children)
    }
  }
  fn(userMenus)
  return mapRoutes
}

/**
 * 将匹配出的菜单注册路由
 */
export function matchRoutes(userMenus: any) {
  if (userMenus) {
    userMenus = userMenus as Menu[]
    const routes: RouteRecordRaw[] = mapRoute(userMenus)
    routes.forEach((route) => router.addRoute('layout', route))
  }
}
